<template>
  <a-modal
    :visible="visible"
    title="学习计划设置"
    :footer="null"
    width="900px"
    :closable="true"
    @cancel="handleCancel"
  >
    <div class="plan-config-container">
      <a-form :model="formState" layout="vertical">
        <!-- 计划列表 -->
        <div v-for="(plan, index) in formState.plans" :key="index" class="plan-row-visual">
          <a-form-item
            :name="['plans', index, 'mainPlanName']"
            :rules="[{ required: true, message: '!' }]"
            class="plan-input-item main-plan-input no-wrap-item"
            :data-index="index"
          >
            <a-input v-model:value="plan.mainPlanName" placeholder="主计划名称" />
          </a-form-item>

          <span class="static-text no-wrap-item">的</span>

          <a-form-item
            :name="['plans', index, 'subPlanName']"
            :rules="[{ required: true, message: '!' }]"
            class="plan-input-item sub-plan-input no-wrap-item"
            :data-index="index"
          >
            <a-input v-model:value="plan.subPlanName" placeholder="子计划 - 子计划" />
          </a-form-item>

          <span class="static-text date-label no-wrap-item">打卡起始时间:</span>

          <a-form-item
            :name="['plans', index, 'startTime']"
            :rules="[{ required: true, message: '!' }]"
            class="plan-datepicker-item no-wrap-item"
          >
            <a-date-picker
              v-model:value="plan.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="-/-/-"
              style="width: 100%;"
            />
          </a-form-item>

          <MinusCircleOutlined
            class="delete-plan-icon no-wrap-item"
            @click="removePlan(index)"
          />
        </div>

        <a-form-item style="margin-top: 10px;">
          <a-button type="dashed" block @click="addPlan">
            <PlusOutlined />
            增加计划
          </a-button>
        </a-form-item>
      </a-form>

      <div class="footer-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleConfirm">确定</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { reactive, defineProps, defineEmits, watch } from 'vue';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  classData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'confirm', 'cancel']);

// formState现在是一个包含多个计划对象的数组
const formState = reactive({
  plans: []
});

const resetForm = () => {
  formState.plans = [];
};

watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 假设 props.classData.studyPlan 是一个计划对象数组
    if (props.classData && Array.isArray(props.classData.studyPlan)) {
      formState.plans = props.classData.studyPlan.map(p => ({
        mainPlanName: p.mainPlanName || '',
        subPlanName: p.subPlanName || '',
        startTime: p.startTime ? dayjs(p.startTime) : null
      }));
    } else {
      resetForm();
      // 如果旧数据不是数组，或者需要从更复杂的旧结构解析，则在这里添加逻辑
      // 例如，如果需要一个默认的空行来开始：
      // addPlan(); 
    }
    if (formState.plans.length === 0) { // 确保至少有一个空行供用户输入
        addPlan();
    }
  } else {
    resetForm();
  }
}, { immediate: true });

// addPlan现在向plans数组添加一个新的完整计划对象
const addPlan = () => {
  formState.plans.push({
    mainPlanName: '',
    subPlanName: '',
    startTime: null
  });
};

// removePlan根据索引从plans数组中移除计划对象
const removePlan = (index) => {
  formState.plans.splice(index, 1);
};

const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
  resetForm();
};

const handleConfirm = () => {
  // 通过表单验证规则显示错误提示，不再使用警告弹窗
  // 检查每个计划项是否填写了必填字段
  let hasEmptyFields = false;
  
  formState.plans.forEach((plan, index) => {
    // 清除可能的旧错误状态
    const mainPlanNameField = document.querySelector(`.main-plan-input[data-index="${index}"] .ant-form-item-control`);
    const subPlanNameField = document.querySelector(`.sub-plan-input[data-index="${index}"] .ant-form-item-control`);
    
    if (mainPlanNameField) {
      mainPlanNameField.classList.remove('ant-form-item-has-error');
    }
    
    if (subPlanNameField) {
      subPlanNameField.classList.remove('ant-form-item-has-error');
    }
    
    // 检查主计划名称
    if (!plan.mainPlanName || plan.mainPlanName.trim() === '') {
      if (mainPlanNameField) {
        mainPlanNameField.classList.add('ant-form-item-has-error');
        
        // 添加错误提示文本
        let errorDiv = mainPlanNameField.querySelector('.ant-form-item-explain');
        if (!errorDiv) {
          errorDiv = document.createElement('div');
          errorDiv.className = 'ant-form-item-explain ant-form-item-explain-error';
          mainPlanNameField.appendChild(errorDiv);
        }
        errorDiv.innerHTML = '<div class="ant-form-item-explain-error">请输入主计划名称</div>';
      }
      hasEmptyFields = true;
    }
    
    // 检查子计划名称
    if (!plan.subPlanName || plan.subPlanName.trim() === '') {
      if (subPlanNameField) {
        subPlanNameField.classList.add('ant-form-item-has-error');
        
        // 添加错误提示文本
        let errorDiv = subPlanNameField.querySelector('.ant-form-item-explain');
        if (!errorDiv) {
          errorDiv = document.createElement('div');
          errorDiv.className = 'ant-form-item-explain ant-form-item-explain-error';
          subPlanNameField.appendChild(errorDiv);
        }
        errorDiv.innerHTML = '<div class="ant-form-item-explain-error">请输入子计划名称</div>';
      }
      hasEmptyFields = true;
    }
  });
  
  if (hasEmptyFields) {
    return; // 有未填写的字段，不提交
  }

  const plansDataToEmit = {
    classId: props.classData.classId,
    studyPlan: formState.plans.map(plan => ({
      mainPlanName: plan.mainPlanName,
      subPlanName: plan.subPlanName,
      startTime: plan.startTime ? plan.startTime.format('YYYY-MM-DD HH:mm:ss') : null
    }))
  };
  
  emit('confirm', plansDataToEmit);
  emit('update:visible', false);
  resetForm();
};

</script>

<style scoped>
.plan-config-container {
  padding: 0 10px;
}

.plan-row-visual {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 8px;
  flex-wrap: nowrap;
}

.static-text {
  white-space: nowrap;
  flex-shrink: 0;
}

.plan-input-item {
  margin-bottom: 0 !important;
  flex-grow: 1;
}
.plan-input-item :deep(.ant-form-item-control-input-content),
.plan-input-item :deep(input),
.plan-datepicker-item :deep(.ant-form-item-control-input-content),
.plan-datepicker-item :deep(.ant-picker) {
    display: flex;
    width: 100% !important;
}

.main-plan-input {
  min-width: 150px;
  flex-grow: 0.5;
  flex-basis: 20%;
}

.sub-plan-input {
  flex-grow: 1;
  flex-basis: 30%;
}

.plan-datepicker-item {
  margin-bottom: 0 !important;
  min-width: 190px;
  flex-shrink: 0;
  flex-basis: 25%;
}

.delete-plan-icon {
  color: red;
  font-size: 18px;
  cursor: pointer;
  flex-shrink: 0;
}

.no-wrap-item {
    flex-shrink: 0;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-form-item-label) {
  padding-bottom: 0 !important;
}

:deep(.ant-form-item) {
  display: flex;
  flex-direction: column;
  margin-bottom: 0 !important;
}

:deep(.ant-form-item-explain) {
  position: absolute;
  bottom: -20px;
  left: 0;
  font-size: 12px;
  width: 100%;
}

</style>